<?php
class Product extends AdminController {
    public function __construct() {
        parent::__construct();
        session_start();
        $_SESSION["KCFINDER"]["disabled"]=false;
        $_SESSION["KCFINDER"]["uploadURL"]=base_url()."uploads/products/";
    }
    
    public function index() {        
        $this->_data["loadPage"]="product/index_view";
        $this->_data["titlePage"]="Quản lý sản phẩm";
        
        $this->session->unset_userdata("sess_search_title");
        $this->session->unset_userdata("sess_search_pricefrom");
        $this->session->unset_userdata("sess_search_priceto");
        $this->session->unset_userdata("sess_search_quantityfrom");
        $this->session->unset_userdata("sess_search_quantityto");
        $this->session->unset_userdata("sess_search_cate");
        $this->session->unset_userdata("sess_search_status");
        
        $this->load->library("cart");
        $this->_data["cart_content"]=$this->cart->contents();
        $this->_data["mess_succ"]=$this->session->flashdata("flash_mess");
        
        $this->load->model("mproduct");
        $this->load->library("pagination");
        $config=array(
            "base_url"=>base_url()."admin_combo/product/index/",
            "total_rows"=>$this->mproduct->countAll(),
            "per_page"=>$this->_data["perpage"],
            "uri_segment"=>4
        );
        $start=$this->uri->segment(4)==""?0:$this->uri->segment(4);
        $this->pagination->initialize($config);
        if($this->mproduct->listAll($config["per_page"], $start) == false)
            $this->_data["info"] = "empty";
        else
            $this->_data["info"]=$this->mproduct->listAll($config["per_page"], $start);
        
        $this->load->view($this->_data["path"], $this->_data);
    }
    
    public function search() {
        $this->_data["loadPage"]="product/search_view";
        $this->_data["titlePage"]="Tìm kiếm sản phẩm";
        
        $title=$this->session->userdata("sess_search_title");
        $pricefrom=$this->session->userdata("sess_search_pricefrom");
        $priceto=$this->session->userdata("sess_search_priceto");
        $quantityfrom=$this->session->userdata("sess_search_quantityfrom");
        $quantityto=$this->session->userdata("sess_search_quantityto");
        $cate=$this->session->userdata("sess_search_cate");
        $status=$this->session->userdata("sess_search_status");
        
        $this->load->helper("menu_cate_helper");
        $this->load->model("mcategory");
        if($this->mcategory->listAll()!=false)
            $this->_data["info_cate"]=$this->mcategory->listAll();
        
        $this->load->helper("status_helper");
        $this->load->model("mstatus");
        if($this->mstatus->listAll()!=false)
            $this->_data["info_status"]=$this->mstatus->listAll();
        
        $this->load->library("cart");
        $this->_data["cart_content"]=$this->cart->contents();
        
        $this->load->model("mproduct");
        $this->load->library("pagination");
        $config=array(
            "base_url"=>base_url()."admin_combo/product/search/",
            "total_rows"=>$this->mproduct->countAllResults($title, $pricefrom, $priceto, $quantityfrom, $quantityto, $cate, $status)["count"],
            "per_page"=>$this->_data["perpage"],
            "uri_segment"=>4
        );
        $start=$this->uri->segment(4)==""?0:$this->uri->segment(4);
        $this->pagination->initialize($config);
        if($this->mproduct->search($title, $pricefrom, $priceto, $quantityfrom, $quantityto, $cate, $status, $config["per_page"], $start) == false)
            $this->_data["info"] = "empty";
        else
            $this->_data["info"]=$this->mproduct->search($title, $pricefrom, $priceto, $quantityfrom, $quantityto, $cate, $status, $config["per_page"], $start);
        
        $this->load->view($this->_data["path"], $this->_data);
    }
    
    public function searchdata() {
        if(isset($_POST["btnSearchProduct"])) {
            $sess=array(
                "sess_search_title"=>$this->input->post("txtTitle"),
                "sess_search_pricefrom"=>$this->input->post("txtPriceFrom"),
                "sess_search_priceto"=>$this->input->post("txtPriceTo"),
                "sess_search_quantityfrom"=>$this->input->post("txtQuantityFrom"),
                "sess_search_quantityto"=>$this->input->post("txtQuantityTo"),
                "sess_search_cate"=>$this->input->post("slCate"),
                "sess_search_status"=>$this->input->post("slStatus")
            );
            $this->session->set_userdata($sess);
            redirect(base_url()."admin_combo/product/search");
        }
    }
    
    public function add() {
        $this->_data["loadPage"]="product/add_view";
        $this->_data["titlePage"]="Thêm sản phẩm";
        
        $this->load->helper("menu_cate_helper");
        $this->load->model("mcategory");
        if($this->mcategory->listAll()!=false)
            $this->_data["info_cate"]=$this->mcategory->listAll();
        
        $this->load->helper("status_helper");
        $this->load->model("mstatus");
        if($this->mstatus->listAll()!=false)
            $this->_data["info_status"]=$this->mstatus->listAll();
        
        $category=$this->input->post("slCate");
        $title=$this->input->post("txtTitle");
        $info=$this->input->post("txtInfo");
        $detail=$this->input->post("txtDetail");
        $price=$this->input->post("txtPrice");
        $quan=$this->input->post("txtQuan");
        $status=$this->input->post("slStatus");
        
        //validate
        $this->load->helper("form");
        $this->load->library("form_validation");
        $this->form_validation->CI =& $this;
        
        $config=array(
            array(
                "field"=>"txtTitle",
                "label"=>"Tên",
                "rules"=>"callback_checkTitle"
            )
        );
        $this->form_validation->set_rules($config);
        
        //add
        if($this->form_validation->run()) {
            $this->load->model("mproduct");
            $data=array(
                    "pro_title"=>$title,
                    "pro_info"=>$info,
                    "pro_detail"=>$detail,
                    "pro_price"=>$price,
                    "pro_quantity"=>$quan,
                    "cate_id"=>$category,
                    "status_id"=>$status
                );
            $flag_file=true;
            if($_FILES["fileImage"]["name"]!="") {
                $config_upload=array(
                    "upload_path"=>"./uploads/product_main/",
                    "allowed_types"=>"gif|jpg|png",
                    "max_size"=>"600",
                    "max_width"=>"1024",
                    "max_height"=>"1024"
                );
                $this->load->library("upload");
                $this->upload->initialize($config_upload);
                if($this->upload->do_upload("fileImage")) {
                    $upload_data=$this->upload->data();
                    $data["pro_img"]=$upload_data["file_name"];
                }else {
                    $flag_file=false;
                    $this->_data["error"]=$this->upload->display_errors();
                }
            }

            if($flag_file) {
                $this->mproduct->insert($data);
                $this->session->set_flashdata("flash_mess", "Thêm sản phẩm thành công.");
                redirect(base_url()."admin_combo/product/");
            }
        }
        
        $this->load->view($this->_data["path"], $this->_data);
    }
    
    public function edit() {
        $this->_data["loadPage"]="product/edit_view";
        $this->_data["titlePage"]="Chỉnh sửa sản phẩm";
        
        //load data
        $this->load->helper("menu_cate_helper");
        $this->load->model("mcategory");
        if($this->mcategory->listAll()!=false)
            $this->_data["info_cate"]=$this->mcategory->listAll();
        
        $this->load->helper("status_helper");
        $this->load->model("mstatus");
        if($this->mstatus->listAll()!=false)
            $this->_data["info_status"]=$this->mstatus->listAll();
        
        $this->load->model("mproduct");
        $id=$this->uri->segment(4);
        $this->_data["info_edit"]=$this->mproduct->getById($id);
        
        //validate
        $this->load->helper("form");
        $this->load->library("form_validation");
        $this->form_validation->CI =& $this;
        
        $config=array(
            array(
                "field"=>"txtTitle",
                "label"=>"Tên",
                "rules"=>"callback_checkTitle"
            )
        );
        $this->form_validation->set_rules($config);
        
        //update
        if($this->form_validation->run()) {
            $category=$this->input->post("slCate");
            $title=$this->input->post("txtTitle");
            $info=$this->input->post("txtInfo");
            $detail=$this->input->post("txtDetail");
            $price=$this->input->post("txtPrice");
            $quan=$this->input->post("txtQuan");
            $status=$this->input->post("slStatus");
            
            $this->load->model("mproduct");
            $data=array(
                    "pro_title"=>$title,
                    "pro_info"=>$info,
                    "pro_detail"=>$detail,
                    "pro_price"=>$price,
                    "pro_quantity"=>$quan,
                    "cate_id"=>$category,
                    "status_id"=>$status
                );
            $flag_file=true;
            if($_FILES["fileImage"]["name"]!="") {
                $config_upload=array(
                    "upload_path"=>"./uploads/product_main/",
                    "allowed_types"=>"gif|jpg|png",
                    "max_size"=>"600",
                    "max_width"=>"1024",
                    "max_height"=>"1024"
                );
                $this->load->library("upload");
                $this->upload->initialize($config_upload);
                if($this->upload->do_upload("fileImage")) {
                    $upload_data=$this->upload->data();
                    $data["pro_img"]=$upload_data["file_name"];
                    $old_img=$this->input->post("txtOldImg");
                    unlink("./uploads/product_main/$old_img");
                }else {
                    $flag_file=false;
                    $this->_data["error"]=$this->upload->display_errors();
                }
            }

            if($flag_file) {
                $this->mproduct->update($data, $id);
                $this->session->set_flashdata("flash_mess", "Chỉnh sửa sản phẩm thành công.");
                redirect(base_url()."admin_combo/product/");
            }
        }
        
        $this->load->view($this->_data["path"], $this->_data);
    }
    
    public function del() {
        $id=$this->uri->segment(4);
        $this->load->model("mproduct");
        $this->mproduct->del($id);
        $this->session->set_flashdata("flash_mess", "Xóa sản phẩm thành công.");
        redirect(base_url()."admin_combo/product/");
    }
    
    public function orderin() {
        $this->load->library("cart");
        //$this->cart->product_name_rules="\.\:\-_ a-z0-9\pL";
        $id=$this->uri->segment(4);
        $qty=0;
        $rowid="";
        $this->load->model("mproduct");
        
        $total_items=$this->cart->total_items();
        if($total_items>0) {
            $this->_data["cart_content"]=$this->cart->contents();
            foreach($this->_data["cart_content"] as $item) {
                if($item["id"]==$id) {
                    $rowid=$item["rowid"];
                    $qty=$item["qty"]+1;
                }
            }
            if($qty==0) 
                $qty=1;
        }else 
            $qty=1;
        if($rowid=="") {
            $pro=$this->mproduct->getById($id);
            if($pro!=false) {
                unset($data_cart);
                $data_cart=array(
                    "id"=>$pro["pro_id"],
                    "qty"=>$qty,
                    "price"=>1,
                    "name"=>url_title($pro["pro_title"])
                );
                if($this->cart->insert($data_cart)) {
                    $this->_data["kq"]="insert thanh cong";
                    $this->session->set_userdata("total_items", $this->cart->total_items());
                }
                else
                    $this->_data["kq"]="insert that bai";
                //$this->_data["cart_content"]=$data_cart;
            }
        }else {
            unset($data_cart);
            $data_cart=array(
                "rowid"=>$rowid,
                "qty"=>$qty
            );
            if($this->cart->update($data_cart))
                $this->_data["kq"]="update thanh cong";
            else
                $this->_data["kq"]="update that bai";
        }
                
        redirect(base_url()."admin_combo/product");
    }
    
    public function show() {
        $this->_data["loadPage"]="product/cart_view";
        $this->_data["titlePage"]="Phiếu nhập";
        
        $this->load->model("mprovider");
        $this->load->helper("provider_helper");
        $this->_data["info_provider"]=$this->mprovider->listAll();
        
        $this->load->library("cart");
        $this->_data["cart_content"]=$this->cart->contents();
        $this->load->view($this->_data["path"], $this->_data);
    }
    
    public function get_unit_price() {
        $prov_id=$this->input->post("slProvider");
        $this->session->set_userdata("sess_prov_id", $prov_id);
        
        $arr=array();
        $this->load->model("mability");
        $this->load->library("cart");
        $this->_data["cart_content"]=$this->cart->contents();
        foreach($this->_data["cart_content"] as $item) {
            if($this->mability->getByProvIdAndProId($prov_id, $item["id"])==false) {
                $data_cart=array(
                    "rowid"=>$item["rowid"],
                    "price"=>1
                );
            }else {
                $ability=$this->mability->getByProvIdAndProId($prov_id, $item["id"]);
                unset($data_cart);
                $data_cart=array(
                    "rowid"=>$item["rowid"],
                    "price"=>$ability["ability_unit_price"]
                );
            }
            $arr[]=$data_cart;
        }
        $this->cart->update_all($arr);
        
        redirect(base_url()."admin_combo/product/show");
    }
    
    public function input_order() {
        $this->load->model("morderin");
        $this->load->model("morderindetail");
        $this->load->library("cart");
        $this->_data["cart_content"]=$this->cart->contents();
        
        $date=date("Y-m-d H:i:s");
        $prov_id=$this->session->userdata("sess_prov_id");
        unset($data_oi);
        $data_oi=array(
            "oi_date"=>$date,
            "oi_price"=>$this->cart->total(),
            "prov_id"=>$prov_id
        );
        $insert_id=$this->morderin->insert($data_oi);
        
        foreach($this->_data["cart_content"] as $item) {
            unset($data_oid);
            $data_oid=array(
                "oi_id"=>$insert_id,
                "pro_id"=>$item["id"],
                "oid_price"=>$item["price"],
                "oid_quantity"=>$item["qty"]
            );
            $this->morderindetail->insert($data_oid);
        }
        
        $this->session->set_flashdata("flash_mess", "Nhập phiếu thành công.");
        $this->load->library("cart");
        $this->cart->destroy();
        $this->session->unset_userdata("total_items");
        $this->session->unset_userdata("sess_prov_id");
        redirect(base_url()."admin_combo/orderin");
    }

    public function cart_destroy() {
        $this->load->library("cart");
        $this->cart->destroy();
        $this->session->unset_userdata("total_items");
        $this->session->unset_userdata("sess_prov_id");
        redirect(base_url()."admin_combo/product");
    }
    
    public function checkTitle($title) {
        $this->load->model("mproduct");
        $id=$this->uri->segment(4);
        if(!$this->mproduct->checkTitle($title, $id)) {
            $this->form_validation->set_message("checkTitle", "Tiêu đề này đã được đăng ký!");
            return false;
        }else
            return true;
    }
}
?>